package com.woniu.controller;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationOutput;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.woniu.entity.UploadResult;
import com.woniu.entity.vo.VedioVO;
import com.woniu.service.AudioProcessingService;
import com.woniu.utils.ResultObj;
import com.woniu.utils.WeblfasrUtils;
import io.minio.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/oss")
public class OssController {
    @Value("${dashscope.api-key}")
    private String dashScopeApiKey;

    @Autowired
    MinioClient minioClient;
    @Autowired
    AudioProcessingService audioProcessingService;

    // 图片上传conv.call
    @PostMapping("/upload")
    public UploadResult upload(@RequestParam("file") MultipartFile file) {
        return uploadFile(file, "java113");
    }

    // 视频上传
    @PostMapping("/upload/video")
    public ResultObj uploadVideo(@RequestParam("video") MultipartFile file) throws JSchException, SftpException, IOException, NoApiKeyException, UploadFileException {
        UploadResult uploadResult = uploadFile(file, "java113-videos");
        VedioVO vo = new VedioVO();
        vo.setFileName(uploadResult.getFileName());
        vo.setFileUrl(uploadResult.getFileUrl());
//        File toAudio = audioProcessingService.processVideoToAudio(file);
//        String content = WeblfasrUtils.getContent(toAudio);
//        vo.setContent(content);
        String content = VideoCoverText(file);
        vo.setContent(content);
        return ResultObj.ok().data(vo);
//        return uploadFile(file,"java-videos");
    }
    // 视频转文本
    public String VideoCoverText(MultipartFile file) throws JSchException, SftpException, IOException, NoApiKeyException, UploadFileException {
//        UploadResult uploadResult = uploadFile(file, "java113-videos");
//        uploadResult.getFileUrl();
//        uploadResult.getFileName();
        //视频转音频
        String toAudio = audioProcessingService.processVideoToAudio(file);
        //音频上传
//        UploadResult uploadResult1 = uploadFile(toAudio, "java113-videos");
//        System.out.println(uploadResult1.getFileUrl());
//        String content = alyServie.VideoCoverText(uploadResult1);
//        String content = WeblfasrUtils.getContent(toAudio);
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(new HashMap<String, Object>(){{put("audio", toAudio);}},
                        new HashMap<String, Object>(){{put("text", "提取这段音频的所有文字");}}))
                .build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .model("qwen-audio-turbo-latest")
                .message(userMessage)
                .apiKey(dashScopeApiKey)
                .build();
        MultiModalConversationResult result = conv.call(param);
        String content = extractTextFromResult(result);
//        System.out.println(JsonUtils.toJson(result));
//        return JsonUtils.toJson(result);
        return content;
    }

    // 通用的文件上传方法
    private UploadResult uploadFile(MultipartFile file, String bucketName) {
        String fileName = file.getOriginalFilename();
        long size = file.getSize();
        try {
            InputStream inputStream = file.getInputStream();

            // 检查存储桶是否存在，不存在则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            // 上传文件
            ObjectWriteResponse oss = minioClient.putObject(
                    PutObjectArgs.builder()
                            .stream(inputStream, size, -1L)
                            .object(fileName)
                            .bucket(bucketName)
                            .build()
            );

            // 获取文件访问URL
            String url = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(bucketName)
                            .object(fileName)
                            .build());

            return new UploadResult(oss.object(), url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static String extractTextFromResult(MultiModalConversationResult result) {
        if (result != null && result.getOutput() != null && !result.getOutput().getChoices().isEmpty()) {
            MultiModalConversationOutput.Choice choice = result.getOutput().getChoices().get(0);
            if (choice.getMessage() != null && !choice.getMessage().getContent().isEmpty()) {
                Object content = choice.getMessage().getContent().get(0);
                if (content instanceof Map) {
                    Map<String, String> contentMap = (Map<String, String>) content;
                    return contentMap.get("text");  // ✅ 只返回 text 的值
                }
            }
        }
        return null; // 如果没有找到 text 内容则返回 null 或者抛出异常
    }
}
